#!/bin/sh
set -e
CMD=$1
APP=$2
#DIR=/usr/local/nodeapps/apps
DIR=/home/mikeliang/nodeapps
PREFIX=$DIR/lib/node_modules
APPDIR=$DIR/apps/$APP
NODE=$DIR/bin/node

green='\e[0;32m'
endColor='\e[0m'

do_show() {
    echo "Running processes: [" $APP "]"
    ps ax | grep $APP | grep -v grep | grep -v "node.sh show"
}

do_start() {
    echo "Starting application " $APP
    echo NODE_PATH=$PREFIX $NODE $APPDIR/app.js &
    NODE_PATH=$PREFIX $NODE $APPDIR/app.js &
    echo $! > $APPDIR/app.pid
    sleep 2
}

do_restart() {
    echo "Restarting application " $APP
    do_stop
    do_start
    #kill -USR1 `cat $APPDIR/app.pid`
}

do_stop() {
    echo "Stopping application " $APP
    echo kill -TERM `cat $APPDIR/app.pid`
    kill -TERM `cat $APPDIR/app.pid`
    rm -f $APPDIR/app.pid
}

do_init() {
    echo "Initializing application environment..."
    set -e
    INIT_DIR=$2
    [ -n $INIT_DIR ] && INIT_DIR=nodeapps
    [ -d "$INIT_DIR" ] || mkdir $INIT_DIR
    cd $INIT_DIR
    mkdir apps bin lib
    cp `which node` bin
    cp ./node.sh $INIT_DIR
    cd lib
    npm install express socket.io
    cd $INIT_DIR
}

do_create() {
    echo "Creating application [$APP]..."
    set -e
    [ -f "$NODE" ] || do_init
    cd $DIR/apps
    $DIR/lib/node_modules/express/bin/express $APP
}

do_usage() {
    echo "Usage:"
    echo "    ./node.sh start myapp"
    echo "    ./node.sh stop myapp"
    echo "    ./node.sh restart myapp"
    echo "    ./node.sh show myapp"
    echo "    ./node.sh init"
    echo "    ./node.sh create myapp"
}


if [ -n "$APP" ] && [ ! -d "$APPDIR" ] && [ "$APP" != "all" ] && [ "$CMD" != "create" ]
then
    echo -n "No such app! Available apps: "
    cd $APPDIR/../
    for i in *;
    do
        if test -d $i; then 
            echo -n -e " $green$i$endColor";
        fi;
    done
    echo 
    exit 1
fi

case "$CMD" in
show)
    do_show
    ;;
start)
    do_start
    ;;
restart)
    do_restart
    ;;
stop)
    do_stop
    ;;
init)
    do_init
    ;;
create)
    do_create
    ;;
*)
    do_usage
    exit 1
    ;;
esac

exit $?


